package com.mall.web.control.jiance;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.client.ps.PsService;
import com.mall.pojo.PsCode;
import com.mall.pojo.PsItem;
import com.mall.web.util.HttpUtil;
import com.mall.web.vo.ResponseEntity;

@Controller
@RequestMapping("/qingqiu/")
public class LunwenResultController {
	@Autowired
	private PsService psService;
	
	
	
	
	/**
	 * 用戶提取鏈接和密碼
	 * @param request
	 * @param response
	 * @param modelMap
	 */
	
	@RequestMapping("queryResult")
	@ResponseBody
	public void queryResult(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		String callback = request.getParameter("callback");
		ResponseEntity<PsItem> responseEntity = new ResponseEntity<>();
		String code = HttpUtil.getStringValueFromRequest(request, "jianceCode");
		String psItemCode = HttpUtil.getStringValueFromRequest(request, "psItemCode");
		PsItem psItem = this.psService.getPsItemByCode(psItemCode);//提取ps商品详情
		if(code.length() != 16){
			responseEntity.initErrorResponseEntity(null, "error");
			responseEntity.setCode("-300");
			HttpUtil.ajaxJsonpOutput(callback, responseEntity, response);
			return ;
		}
		
		if(psItem == null){
			responseEntity.initErrorResponseEntity(null, "error");
			HttpUtil.ajaxJsonpOutput(callback, responseEntity, response);
			return ;
		}
		
		PsCode psCode = this.psService.getPsCodeByCode(code);//校验订单编号是否使用过
		if (psCode !=null && psCode.getId()>0) {
			responseEntity.initErrorResponseEntity(null, "error");
			responseEntity.setCode("-400");
			HttpUtil.ajaxJsonpOutput(callback, responseEntity, response);
			return ;
		}
		
		psCode = new PsCode();
		psCode.setCode(code);
		psCode.setStatus("使用");
		psCode.setGmtCreate(new Date());
		psCode.setGmtModify(new Date());
		this.psService.insertPsCode(psCode);//使用过的订单编号插入数据库

		responseEntity.initSuccResponseEntity(psItem, "succ");
		HttpUtil.ajaxJsonpOutput(callback, responseEntity, response);
	}
	/**
	 * 校验订单编号是否使用
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("checkCode")
	@ResponseBody
	public ResponseEntity<PsCode> checkCode(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		String code = HttpUtil.getStringValueFromRequest(request, "jianceCode");
		ResponseEntity<PsCode> responseEntity = new ResponseEntity<>();
		PsCode psCode = this.psService.getPsCodeByCode(code);
		responseEntity.initSuccResponseEntity(psCode, "request success");
		return responseEntity;
		
	}
	

}
